package com.sino.config.server.controller.endpoint;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.nutz.lang.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import com.sino.config.server.model.Config;
import com.sino.config.server.service.ConfigService;
import com.sino.config.server.service.ProfileChecker;

/**
 * @author kerbores
 *
 */
@RestController
public class ConfigServerEndpoint {

    @Autowired
    ConfigService configService;

    @Autowired
    ProfileChecker profileChecker;

    @Autowired
    HttpServletRequest request;

    @Autowired
    HttpServletResponse response;

    @GetMapping("{application}/{profile}/{label}")
    public Config config(@PathVariable("application") String application,
                         @PathVariable(value = "profile", required = false) String profile,
                         @PathVariable(value = "label", required = false) String label) {
        if (Strings.isBlank(profile)) {
            profile = "dev";
        }
        if (Strings.isBlank(label)) {
            label = "default";
        }
        if (!profileChecker.check(request, profile)) {
            response.setStatus(401);
            response.setHeader("Cache-Control", "no-store");
            response.setDateHeader("Expires", 0);
            response.setHeader("WWW-authenticate", "Basic Realm=\"config\"");
            return null;
        }
        return configService.loadConfig(application, profile, label);
    }
}
